package com.quanjiaolian.login.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.quanjiaolian.login.service.LoginService;
import com.quanjiaolian.login.serviceimpl.LoginServiceImpl;
import com.quanjiaolian.tools.ResponseToJson;
import com.quanjiaolian.tools.SendTemplateSMS;

/**
 * 用户注册action
 * @author Herson_Li
 *
 */
@SuppressWarnings("serial")
public class RegisterAction extends HttpServlet {

	/**
	 * 声明Log4j变量
	 */
	public static ResourceBundle resourceBundle = null;
	static Logger logger = Logger.getLogger(RegisterAction.class.getName());
	
	Map<String,Object> resultMap = new HashMap<String,Object>();
	LoginService ls = new LoginServiceImpl();
	/**
	 * 向新用户发送短信验证码进行注册
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		try{
			String msisdn = request.getParameter("msisdn");
			String user_type = request.getParameter("user_type");
			int i = ls.isRegister(msisdn, user_type);
			if(i>0){
				resultMap.put("result","this msisdn has been bound");
			}else{
				Map<String,Object> map = SendTemplateSMS.sendSMS(msisdn);
				resultMap.put("result",map);
			}
		}catch (Exception e) {
			resultMap.put("result","Error");
			logger.info(e);
			e.printStackTrace();
		}
		ResponseToJson.responseOutWithJson(response, resultMap);
	}

	/**
	 * 将新用户注册信息入库
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			request.setCharacterEncoding("utf-8");
			String msisdn = request.getParameter("msisdn");
			String user_type = request.getParameter("user_type");
			String passwd = request.getParameter("passwd");
			String user_name = request.getParameter("user_name");
			if(msisdn == null || "".equals(msisdn)){
				resultMap.put("result","Error");
			}else if(user_type == null || "".equals(user_type)){
				resultMap.put("result","Error");
			}else if(passwd == null || "".equals(passwd)){
				resultMap.put("result","Error");
			}else{
				int i = ls.insertNewUser(msisdn, passwd, user_type, user_name);
				if(i>0){
					resultMap.put("result","OK");
				}else{
					resultMap.put("result","Failed");
				}
			}
			
			
			ResponseToJson.responseOutWithJson(response, resultMap);
	}

}
